package com.xlh.support.attendance.controller;

import com.xlh.common.Result;
import com.xlh.support.attendance.po.AttendanceListQueryPO;
import com.xlh.support.attendance.service.AttendanceService;
import com.xlh.support.attendance.service.AttendanceStatisticsService;
import com.xlh.support.attendance.vo.AttendanceVO;
import com.xlh.vo.PageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author cheer
 */
@Api(tags = "AttendanceStatisticsController", description = "学生考勤")
@RestController
@RequestMapping("/attendance/statistics")
public class AttendanceStatisticsController {

    @Autowired
    private AttendanceService attendanceService;

    @Autowired
    private AttendanceStatisticsService attendanceStatisticsService;

    @ApiOperation("查询考勤统计")
    @PostMapping
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result<PageVO<AttendanceVO>> statistics(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                   @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                   @RequestBody @Valid AttendanceListQueryPO attendanceListQueryPO) {
        List<AttendanceVO> attendanceVOs = attendanceService.listAttendanceStudents(attendanceListQueryPO, true);

        PageVO<AttendanceVO> pageVO = PageVO.<AttendanceVO>builder()
                .pageNum(pageNum)
                .pageSize(pageSize)
                .total(attendanceVOs.size())
                .pages(attendanceVOs.size() == 0 ? 0 : attendanceVOs.size() / (pageSize + 1))
                .content(attendanceVOs.subList((pageNum - 1) * pageSize, Math.min(pageNum * pageSize, attendanceVOs.size())))
                .build();

        return Result.success(pageVO);
    }

    @ApiOperation("下载考勤信息")
    @PostMapping("/download")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result download(@RequestBody @Valid AttendanceListQueryPO attendanceListQueryPO) {
        attendanceStatisticsService.download(attendanceListQueryPO);
        return null;
    }

}
